package tech.yunland.shop.domain.service;

import com.moyuer.bsf.common.web.AuthToken;
import com.moyuer.bsf.domain.model.HqlArgs;
import com.moyuer.bsf.domain.model.User;
import com.moyuer.bsf.domain.model.UserOrgans;
import com.moyuer.bsf.domain.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.yunland.shop.domain.dao.MessSendRecordDao;
import tech.yunland.shop.domain.model.MessSendRecord;
import tech.yunland.weixin.domain.service.ICommonServices;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author 文卡<wkwenka@gmail.com>  on 17-3-4.
 */
@Service
public class MessSendRecordService implements ICommonServices {

    @Autowired
    private MessSendRecordDao messSendRecordDao;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private UserService userService;


    /**
     * 保存发送记录
     *
     * @param title              标题
     * @param content_source_url 内容地址
     * @param content            内容
     * @param digest             图文消息描述
     * @param show_cover_pic     是否显示封面
     */
    @Override
    public void saveSendInfo(String title, String content_source_url, String content, String digest, String show_cover_pic, String message) {
        MessSendRecord messSendRecord = new MessSendRecord();

        messSendRecord.setMessage(message);
        if (message.contains("成功")) {
            messSendRecord.setState(Integer.valueOf(1));
        } else if (message.contains("失败")) {
            messSendRecord.setState(Integer.valueOf(0));
        }
        messSendRecord.setTitle(title);
        messSendRecord.setContent_source_url(content_source_url);
        messSendRecord.setContent(content);
        messSendRecord.setDigest(digest);
        messSendRecord.setShow_cover_pic(show_cover_pic);

        //获取当前用户
        Object o = request.getAttribute("authToken");
        if (o != null) {
            AuthToken authToken = (AuthToken) o;
            String uid = authToken.getUid();
            User user = userService.get(uid);
            messSendRecord.setCreator(user);
            messSendRecord.setAuthor(user.getName());

            //获取组织
            if (user != null) {
                Set<UserOrgans> userOrgans = user.getUserOrgans();
                for (UserOrgans userOrgan : userOrgans) {
                    if (userOrgan.getIsPrimary()) {
                        messSendRecord.setOrgan(userOrgan.getOrgan());
                        break;
                    }
                }
            } else {
                throw new RuntimeException("当前登录信息失效，请重新登录");
            }
        }
        messSendRecordDao.save(messSendRecord);
    }

    private HqlArgs getHqlArgs(String param, List<String> organIds, List<Integer> states) {

        param = StringUtils.trimToEmpty(param);

        Map<String, Object> args = new HashMap<>();

        String hql = "FROM MessSendRecord record WHERE 1=1 ";

        if (StringUtils.isNotBlank(param)) {
            hql += " AND (record.title LIKE :param OR " +
                    "record.author LIKE :param OR " +
                    "record.content_source_url LIKE :param OR " +
                    "record.content LIKE :param OR " +
                    "record.digest LIKE :param OR " +
                    "record.show_cover_pic LIKE :param)";
            args.put("param", "%" + param + "%");
        }

        if (organIds != null) {
            if (organIds.size() == 1) {
                hql += " AND record.organ.id = :organid";
                args.put("organid", organIds.get(0));
            } else {
                hql += " AND record.organ.id in :organid";
                args.put("organid", organIds);
            }
        }

        if (states != null) {
            if (states.size() == 1) {
                hql += " AND record.state = :state";
                args.put("state", states.get(0));
            } else {
                hql += " AND record.state in :states";
                args.put("states", states);
            }
        }


        return new HqlArgs(hql, args);
    }

    /**
     * 查询所有记录
     *
     * @param param
     * @param organIds
     * @param states
     * @param start
     * @param rows
     * @return
     */
    public List<MessSendRecord> getRecordList(String param, List<String> organIds, List<Integer> states, Integer start, Integer rows) {
        HqlArgs hqlArgs = getHqlArgs(param, organIds, states);
        String s = hqlArgs.getHql() + " ORDER BY record.createTime DESC";
        List<MessSendRecord> messSendRecords = messSendRecordDao.findByNamedParam(s, start, rows, hqlArgs.getArgs());
        return messSendRecords;
    }


    /**
     * 查询记录总数
     *
     * @param param
     * @param organIds
     * @param states
     * @return
     */
    public int getRecordListSize(String param, List<String> organIds, List<Integer> states) {
        HqlArgs hqlArgs = getHqlArgs(param, organIds, states);
        return (int) messSendRecordDao.getCount(hqlArgs.getHql(), hqlArgs.getArgs());

    }

    /**
     * 通过 消息记录 Id 查看消息记录详情
     *
     * @param id
     * @return
     */
    public MessSendRecord getInfoById(String id) {
        MessSendRecord messSendRecord = messSendRecordDao.get(id);
        return messSendRecord;
    }

    /**
     * 标记删除记录
     *
     * @param id
     */
    public void delRecord(String id) {
        MessSendRecord messSendRecord = messSendRecordDao.get(id);
        if (messSendRecord != null && messSendRecord.getState().intValue() != -1) {
            messSendRecord.setState(Integer.valueOf(-1));
            messSendRecordDao.update(messSendRecord);
        } else {
            throw new RuntimeException("该记录已经删除");
        }
    }

}